__all__ = [
    'BASE_DIR',
    'Config',
    'LogConfig',
    'ServiceConfig',
    'RedisConfig',
    "ORM_LINK_CONF",
]

import os
from pathlib import Path
from functools import lru_cache
import tomllib
# import pytomlpp
# import tomli
from conf.const import EnvConst
from conf.setting import (
    Setting, ORMSetting
)

BASE_DIR = Path(__file__).absolute().parent


@lru_cache()
def get_settings() -> Setting:
    code_env = os.environ.get('CODE_ENV', EnvConst.LOCAL)

    if code_env == EnvConst.TEST:
        p = Path(BASE_DIR).joinpath('conf/test.local.toml')
        if not p.is_file():
            p = Path(BASE_DIR).joinpath('conf/test.toml')
    elif code_env == EnvConst.PRD:
        p = Path(BASE_DIR).joinpath('conf/product.local.toml')
        if not p.is_file():
            p = Path(BASE_DIR).joinpath('conf/product.toml')
    elif code_env == EnvConst.DEV:
        p = Path(BASE_DIR).joinpath('conf/dev.local.toml')
        if not p.is_file():
            p = Path(BASE_DIR).joinpath('conf/dev.toml')
    else:
        p = Path(BASE_DIR).joinpath('conf/local.toml')

        # os.environ['https_proxy'] = 'http://@127.0.0.1:7890'

    print(f'当前环境变量 CODE_ENV={code_env}, 需要读取 {p.absolute()}')

    if not p.is_file():
        raise Exception('config no exists')

    with open(p, "rb") as f:
        config_data = tomllib.load(f)
    settings = Setting.model_validate(config_data)
    return settings


Config = get_settings()
ORM_LINK_CONF = ORMSetting(Config.db).orm_link_conf
# 日志，fastapi服务配置
LogConfig = Config.log
ServiceConfig = Config.service
RedisConfig = Config.redis

